<?php
	// This is the class that controls the communication with the tellstick
	
	class Tellstick {
	
		public $number_of_devices;
		public $devices;

		// Create object and get the current devices and their statuses
		public function __construct() {
			$this->get_devices();
		}

		// Update device statuses
		public function set_devices($request) {
			
			foreach($request['device_list'] as $device => $status) :

				$status = $status == 1 ? 'on' : 'off';

				$argument .= " --$status $device ";

			endforeach;

			if($argument != '')
				exec('"' . TDTOOL . '"' . $argument);

			return $this->check_status($request['device_list']);
		}

		// Check device statuses and compare them with the request
		public function check_status($requested_statuses)
		{
			$this->get_devices();

			foreach($requested_statuses as $device_id => $requested_status)
				if($this->devices[$device_id]['status'] != $requested_status)
					return false;
			
			return true;
		}

		// Run tdtool and get a list of devices and their statuses.
		private function get_devices() {

			exec('"' . TDTOOL . '" --list', $tdtool_output);

			foreach($tdtool_output as $line) :
			
				if($colon_position = strpos($line, ':')) :
					$this->number_of_devices = trim(substr($line, $colon_position+1));
				else :
					$columns = explode("\t", $line);
					$this->devices[$columns[0]] = array('id'     => $columns[0],
														'type'   => 'switch',
					                                    'name'   => utf8_encode($columns[1]),
					                                    'status' => $columns[2] == 'ON' ? 1 : 0);
				endif;
			
			endforeach;
		}
	}
?>
